package com.ilarele.shopping.client.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.flurry.android.FlurryAgent;
import com.ilarele.shopping.Message;
import com.ilarele.shopping.Product;
import com.ilarele.shopping.ProductComment;
import com.ilarele.shopping.ProductInfo;
import com.ilarele.shopping.ProductLocation;
import com.ilarele.shopping.client.R;
import com.ilarele.shopping.client.adaptors.A1CommentsAdapter;
import com.ilarele.shopping.client.adaptors.A1ProductAdapter;
import com.ilarele.shopping.client.adaptors.Sorter;
import com.ilarele.shopping.client.util.Communication;
import com.ilarele.shopping.client.util.DBUtil;
import com.ilarele.shopping.client.util.DrawableManager;
import com.ilarele.shopping.client.util.Flip3dAnimation;
import com.ilarele.shopping.client.util.Global;
import com.ilarele.shopping.client.util.IntentIntegrator;
import com.ilarele.shopping.client.util.IntentResult;

public class A1OthersInfoActivity extends Activity {

	private static final int DIALOG_SORT_CRITERIA = 0;
	protected static final int DIALOG_NEW_PROD = 2;
	protected static final int DIALOG_COMMENT = 3;

	protected static final int RESULT_MAP_VIEW = 1;
	protected static final int RESULT_TAKE_PICTURE = 2;

	protected static final String NO_MORE_DATA = "No more data";

	private A1ProductAdapter mShoppingListAdapter;
	private int mFilter;
	private boolean mIsDetailsView = false;
	private ListView mShoppingList;
	protected int mDetailsPosition;
	// private Random rand = new Random();

	// Detailed view
	private View mRoot;
	private View mAllView;
	private View mOneView;
	protected Product mDialogProd = new Product();
	private ListView oneCommList;
	private Button oneSubmit;
	private Button oneExternInfo;

	// picture
	private ImageView onePicture;
	private ImageView oneOkPicture;
	private ImageView onePrevPicture;
	private ImageView oneNextPicture;

	// name
	private TextView oneName;
	private ImageView oneOkName;
	private ImageView oneNextName;
	private ImageView onePrevName;

	// info
	private SeekBar oneRatingbar;
	private Button oneLocation;
	private TextView onePrice;
	private ImageView oneOkInfo;
	private ImageView onePrevInfo;
	private ImageView oneNextInfo;

	// comments
	private Button onePostComm;
	private Button oneShowComm;
	private Button onePostFacebook;
	private A1CommentsAdapter oneCommAdapter;

	private TextView oneTags;
	private ImageView oneOkTags;
	private ImageView oneNextTags;
	private ImageView onePrevTags;

	private TextView toUpdatePlace;
	private ProductLocation updateLocation;
	private String updatePicPath;
	private ImageView initProductPicture;
	private EditText filterText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a1_others_tab);
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		final Button setSortOrder = (Button) findViewById(R.id.sort_crit_btn);
		setSortOrder.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showDialog(DIALOG_SORT_CRITERIA);
			}
		});
		mRoot = findViewById(R.id.list_item_root);
		mAllView = findViewById(R.id.shopping_list_layout);
		mOneView = findViewById(R.id.item_details_root);

		final Button moreBtn = new Button(this);
		moreBtn.setTextAppearance(A1OthersInfoActivity.this,
				R.style.pink_button_style);
		moreBtn.setBackgroundResource(R.drawable.blue_button);
		moreBtn.setText(R.string.refresh);
		moreBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				refreshList();

			}
		});

		mShoppingList = (ListView) findViewById(R.id.shopping_list);
		mShoppingList.addFooterView(moreBtn);
		ArrayList<Product> items = new ArrayList<Product>();

		mShoppingListAdapter = new A1ProductAdapter(this, items);

		mShoppingList.setAdapter(mShoppingListAdapter);
		mShoppingList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mDetailsPosition = position;
				SetDetailsView(mShoppingListAdapter.getItem(position));
				animateToDetailsView();
			}
		});

		final ImageView sortAscBtn = (ImageView) findViewById(R.id.sort_asc_btn);
		final ImageView sortDescBtn = (ImageView) findViewById(R.id.sort_desc_btn);
		final ImageView sortRandBtn = (ImageView) findViewById(R.id.sort_rand_btn);

		sortAscBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sortDescBtn.setImageResource(R.drawable.down_unsel);
				sortRandBtn.setImageResource(R.drawable.random_unsel);
				sortAscBtn.setImageResource(R.drawable.up_sel);
				mShoppingListAdapter.setSortDirection(Sorter.SORT_DIR_ASC);
			}
		});

		sortDescBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sortDescBtn.setImageResource(R.drawable.down_sel);
				sortRandBtn.setImageResource(R.drawable.random_unsel);
				sortAscBtn.setImageResource(R.drawable.up_unsel);
				mShoppingListAdapter.setSortDirection(Sorter.SORT_DIR_DESC);
			}
		});

		sortRandBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sortDescBtn.setImageResource(R.drawable.down_unsel);
				sortAscBtn.setImageResource(R.drawable.up_unsel);
				sortRandBtn.setImageResource(R.drawable.random_sel);
				mShoppingListAdapter.setSortDirection(Sorter.SORT_DIR_RANDOM);
			}
		});
		
		filterText = (EditText) findViewById(R.id.input_filter_query);
		filterText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence text, int arg1, int arg2,
					int arg3) {
				mShoppingListAdapter.refreshFilter(text.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable text) {
			}
		});

		initDetailsView();
		refreshList();
	}

	private void initDetailsView() {
		oneCommList = (ListView) findViewById(R.id.comments_list);
		oneCommAdapter = new A1CommentsAdapter(this,
				new ArrayList<ProductComment>());
		oneCommList.setAdapter(oneCommAdapter);
		oneRatingbar = (SeekBar) findViewById(R.id.item_rating);

		oneOkPicture = (ImageView) findViewById(R.id.ok_picture);
		oneNextPicture = (ImageView) findViewById(R.id.next_picture);
		onePrevPicture = (ImageView) findViewById(R.id.prev_picture);

		oneOkName = (ImageView) findViewById(R.id.ok_name);
		oneNextName = (ImageView) findViewById(R.id.next_name);
		onePrevName = (ImageView) findViewById(R.id.prev_name);

		oneOkInfo = (ImageView) findViewById(R.id.ok_info);
		oneNextInfo = (ImageView) findViewById(R.id.next_info);
		onePrevInfo = (ImageView) findViewById(R.id.prev_info);

		oneOkTags = (ImageView) findViewById(R.id.ok_tags);
		onePrevTags = (ImageView) findViewById(R.id.prev_tags);
		oneNextTags = (ImageView) findViewById(R.id.next_tags);

		onePicture = (ImageView) findViewById(R.id.item_picture);
		oneSubmit = (Button) findViewById(R.id.item_submit);
		oneExternInfo = (Button) findViewById(R.id.item_extern_info);
		oneName = (TextView) findViewById(R.id.item_name);
		oneLocation = (Button) findViewById(R.id.item_show_location);
		onePrice = (TextView) findViewById(R.id.item_price);
		oneTags = (TextView) findViewById(R.id.item_tags);

		onePostComm = (Button) findViewById(R.id.post_comment);
		oneShowComm = (Button) findViewById(R.id.show_comments);
		onePostFacebook = (Button) findViewById(R.id.post_faceebok);
	}

	protected void refreshList() {
		if (!Global.isConnectedToInternet(this)) {
			Toast.makeText(this, R.string.please_connect, Toast.LENGTH_SHORT);
			return;
		}
		ArrayList<Product> prods = Communication.sendFilteredMessage();
		runOnUiThread(new Runnable() {
			public void run() {
				mShoppingListAdapter.clear();
				mShoppingListAdapter.notifyDataSetChanged();
			}
		});
		for (final Product simpleProd : prods) {
			DBUtil.fillRate(this, simpleProd);
			runOnUiThread(new Runnable() {
				public void run() {
					mShoppingListAdapter.add(simpleProd);
					mShoppingListAdapter.notifyDataSetChanged();
				}
			});
		}
		filterText.setText("");
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		if (!mIsDetailsView)
			getMenuInflater().inflate(R.menu.products, menu);
		else
			getMenuInflater().inflate(R.menu.details, menu);
		return super.onPrepareOptionsMenu(menu);
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final Dialog dialog;
		switch (id) {
		case DIALOG_SORT_CRITERIA:
			final CharSequence[] itemsFilter = { Global.SORT_DATE,
					Global.SORT_LOCATION, Global.SORT_PRICE };

			builder.setTitle("Sort by:");
			builder.setSingleChoiceItems(itemsFilter, 0,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							mShoppingListAdapter.setSortCriteria(item);
							dialog.cancel();
						}
					});
			return builder.create();
		case DIALOG_NEW_PROD: {
			dialog = new Dialog(this);

			dialog.setContentView(R.layout.dialog_my_item);
			dialog.setTitle("Init Product");

			initProductPicture = (ImageView) dialog
					.findViewById(R.id.dlg_picture);

			initProductPicture.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(A1OthersInfoActivity.this,
							TakePictureActivity.class);
					startActivityForResult(intent, RESULT_TAKE_PICTURE);
				}
			});

			final EditText name = (EditText) dialog.findViewById(R.id.dlg_name);
			name.setText("");
			final EditText price = (EditText) dialog
					.findViewById(R.id.dlg_price);

			toUpdatePlace = (TextView) dialog.findViewById(R.id.dlg_place);
			final EditText tags = (EditText) dialog.findViewById(R.id.dlg_tags);
			tags.setText("");
			final SeekBar rating = (SeekBar) dialog
					.findViewById(R.id.dlg_rating);
			final Button submit = (Button) dialog.findViewById(R.id.dlg_submit);
			submit.setTextAppearance(A1OthersInfoActivity.this,
					R.style.pink_button_style);
			submit.setBackgroundResource(R.drawable.blue_button);
			submit.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					final Message msg = new Message();
					msg.type = Message.TYPE_CLIENT_INIT_PROD;
					msg.idClient = Global.clientId;
					final Product localProd = mDialogProd;
					localProd.pName.name = name.getText().toString();
					localProd.pInfo.price = Float.parseFloat(price.getText()
							.toString());
					localProd.pTags.tags = tags.getText().toString();
					localProd.pInfo.rating = rating.getProgress();
					if (updateLocation != null) {
						localProd.pInfo.pLocation = updateLocation;
					}
					msg.content = localProd;
					localProd.pPicture.imageUrl = updatePicPath;
					new Thread(new Runnable() {
						@Override
						public void run() {
							Communication.sendMessage(msg, false);
						}
					}).start();

					new Thread(new Runnable() {
						@Override
						public void run() {
							Communication.uploadPicture(updatePicPath);
							updatePicPath = null;
						}
					}).start();
					// add to DB
					DBUtil.insertNewProduct(A1OthersInfoActivity.this,
							localProd);
					// Global.newInsertedItems.add(localProd);
					runOnUiThread(new Runnable() {
						public void run() {
							mShoppingListAdapter.add(localProd);
							mShoppingListAdapter.notifyDataSetChanged();
						}
					});
					mDialogProd = new Product();
					dialog.dismiss();
				}
			});

			final Button changePlace = (Button) dialog
					.findViewById(R.id.dlg_change_place);
			changePlace.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// open a MapView
					Intent intent = new Intent(A1OthersInfoActivity.this,
							CustomEditMapView.class);
					startActivityForResult(intent, RESULT_MAP_VIEW);
				}
			});
			return dialog;
		}
		case DIALOG_COMMENT: {
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.new_comment);

			final EditText name = (EditText) dialog.findViewById(R.id.name);
			final EditText content = (EditText) dialog
					.findViewById(R.id.textarea);

			final Button send = (Button) dialog.findViewById(R.id.send);
			send.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					ProductComment comm = new ProductComment();
					comm.content = content.getText().toString();
					comm.senderName = name.getText().toString();
					mDialogProd.pComments = comm;
					Communication.sendComment(mDialogProd);
					dialog.cancel();
				}
			});
			return dialog;
		}
		default:
			return null;
		}
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add_random:
			addProduct("9787777");
			return true;
		case R.id.menu_scan:
			IntentIntegrator.initiateScan(this);
			return true;
		case R.id.details_menu_back:
			animateFromDetailsView();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void addProduct(String id) {
		Message msg = new Message();
		msg.type = Message.TYPE_CLIENT_ADD_PROD;
		msg.idClient = Global.clientId;
		mDialogProd.idProd = id;
		msg.idProd = id;
		sendProdToServer(msg);
	}

	private void sendProdToServer(final Message msg) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Message msgResponse = Communication.sendMessage(msg, true);
				if (msgResponse.type == Message.TYPE_SERVER_ADD_PROD_NEW) {
					runOnUiThread(new Runnable() {
						public void run() {
							showDialog(DIALOG_NEW_PROD);
						}
					});
				} else if (msgResponse.type == Message.TYPE_SERVER_ADD_PROD_EXISTS) {
					// if the product exists in my list - get it's position
					final Product prod = (Product) msgResponse.content;
					int index = mShoppingListAdapter.getPosition(prod);
					if (index != -1) {
						mDetailsPosition = index;
						// else add it to the top of the list
					} else {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mShoppingListAdapter.addFirst(prod);
								mShoppingListAdapter.notifyDataSetChanged();
							}
						});

						mDetailsPosition = 0;
					}
					DBUtil.insertNewProduct(A1OthersInfoActivity.this,
							prod);

					// open details
					SetDetailsView(prod);
					animateToDetailsView();
				}
			}
		}).start();
	}

	public int getFilter() {
		return mFilter;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (mIsDetailsView && KeyEvent.KEYCODE_BACK == keyCode) {
			animateFromDetailsView();
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

	private void animateToDetailsView() {
		assert (!mIsDetailsView);
		mIsDetailsView = true;

		hideSoftKeyboard(this, mAllView);

		View list = mAllView;
		int cx = mRoot.getWidth() / 2;
		int cy = mRoot.getHeight() / 2;
		final Animation animation = new Flip3dAnimation(list, mOneView, cx, cy,
				true);

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mRoot.startAnimation(animation);
			}
		});
	}

	private void animateFromDetailsView() {
		assert (mIsDetailsView);
		mIsDetailsView = false;
		oneCommAdapter.clear();
		hideSoftKeyboard(this, mAllView);

		View list = mAllView;
		int cx = mRoot.getWidth() / 2;
		int cy = mRoot.getHeight() / 2;
		Animation animation = new Flip3dAnimation(list, mOneView, cx, cy, false);
		animation.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
				if (AdapterView.INVALID_POSITION != mDetailsPosition) {
					ListView list_view = mShoppingList;
					list_view.requestFocus();
					list_view.setSelection(mDetailsPosition);

					Rect rect = new Rect();
					list_view.getFocusedRect(rect);
					list_view.requestChildRectangleOnScreen(list_view, rect,
							false);
				}
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationStart(Animation animation) {
			}
		});
		mRoot.startAnimation(animation);
	}

	public static void hideSoftKeyboard(Context ctx, View view) {
		InputMethodManager manager = (InputMethodManager) ctx
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (null != manager)
			manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	private void SetDetailsView(final Product product) {
		mDialogProd = product;
		final ProductInfo info = product.pInfo;

		oneRatingbar.setProgress(info.rating);
		oneOkPicture
				.setImageResource(getImageResource(product.pPicture.unsavedRate));
		oneOkName.setImageResource(getImageResource(product.pName.unsavedRate));
		oneOkInfo.setImageResource(getImageResource(product.pInfo.unsavedRate));
		oneOkTags.setImageResource(getImageResource(product.pTags.unsavedRate));

		oneOkPicture.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				product.nextImageRate();
				oneOkPicture
						.setImageResource(getImageResource(product.pPicture.unsavedRate));
			}
		});

		oneOkName.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				product.nextNameRate();
				oneOkName
						.setImageResource(getImageResource(product.pName.unsavedRate));
			}
		});

		oneOkInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				product.nextInfoRate();
				oneOkInfo
						.setImageResource(getImageResource(product.pInfo.unsavedRate));
			}
		});

		oneOkTags.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				product.nextTagsRate();
				oneOkTags
						.setImageResource(getImageResource(product.pTags.unsavedRate));
			}
		});

		oneSubmit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Communication.sendRateMessage(A1OthersInfoActivity.this,
						product);
				animateFromDetailsView();
			}
		});
		oneExternInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Global.openProductSearch(product.idProd,
						A1OthersInfoActivity.this);
			}
		});

		DrawableManager.fetchView(product.pPicture.imageUrl, onePicture);
		oneName.setText(product.pName.name);
		oneLocation.setText(info.pLocation.name);
		oneLocation.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(A1OthersInfoActivity.this,
						CustomShowMapView.class);
				intent.putExtra("latitude", info.pLocation.latitude);
				intent.putExtra("longitude", info.pLocation.longitude);
				if (info.pLocation.latitude != 0)
					intent.putExtra("hasLocation", true);
				startActivity(intent);
			}
		});
		onePrice.setText("" + info.price);
		oneTags.setText(product.pTags.tags);

		oneNextPicture.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedPicture(1, product)) {
					DrawableManager.fetchView(product.pPicture.imageUrl,
							onePicture);
					DBUtil.fillPictureRate(A1OthersInfoActivity.this, product);
					oneOkPicture
							.setImageResource(getImageResource(product.pPicture.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), "No more",
							Toast.LENGTH_SHORT).show();
			}
		});
		onePrevPicture.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedPicture(-1, product)) {
					DrawableManager.fetchView(product.pPicture.imageUrl,
							onePicture);
					DBUtil.fillNameRate(A1OthersInfoActivity.this, product);
					oneOkPicture
							.setImageResource(getImageResource(product.pPicture.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), "No more",
							Toast.LENGTH_SHORT).show();
			}
		});

		oneNextName.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedName(1, product)) {
					oneName.setText(product.pName.name);
					DBUtil.fillNameRate(A1OthersInfoActivity.this, product);
					oneOkName
							.setImageResource(getImageResource(product.pName.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), "No more",
							Toast.LENGTH_SHORT).show();
			}
		});
		onePrevName.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedName(-1, product)) {
					oneName.setText(product.pName.name);
					DBUtil.fillNameRate(A1OthersInfoActivity.this, product);
					oneOkName
							.setImageResource(getImageResource(product.pName.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), "No more",
							Toast.LENGTH_SHORT).show();
			}
		});

		oneNextInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedInfo(1, product)) {
					oneLocation.setText(product.pInfo.pLocation.name);
					onePrice.setText("" + product.pInfo.price);
					oneRatingbar.setProgress(product.pInfo.rating);
					DBUtil.fillInfoRate(A1OthersInfoActivity.this, product);
					oneOkInfo
							.setImageResource(getImageResource(product.pInfo.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), NO_MORE_DATA,
							Toast.LENGTH_SHORT).show();
			}
		});

		onePrevInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedInfo(-1, product)) {
					oneLocation.setText(product.pInfo.pLocation.name);
					onePrice.setText("" + product.pInfo.price);
					oneRatingbar.setProgress(product.pInfo.rating);
					DBUtil.fillInfoRate(A1OthersInfoActivity.this, product);
					oneOkInfo
							.setImageResource(getImageResource(product.pInfo.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), NO_MORE_DATA,
							Toast.LENGTH_SHORT).show();
			}
		});

		oneNextTags.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedTags(1, product)) {
					oneTags.setText(product.pTags.tags);
					DBUtil.fillNameTags(A1OthersInfoActivity.this, product);
					oneOkTags
							.setImageResource(getImageResource(product.pTags.unsavedRate));
				} else
					Toast.makeText(getApplicationContext(), NO_MORE_DATA,
							Toast.LENGTH_SHORT).show();
			}
		});

		onePrevTags.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (Communication.getNextRatedTags(-1, product)) {
					oneTags.setText(product.pTags.tags);
					DBUtil.fillNameTags(A1OthersInfoActivity.this, product);
					oneOkTags
							.setImageResource(getImageResource(product.pTags.unsavedRate));
				} else {
					Toast.makeText(getApplicationContext(), NO_MORE_DATA,
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		onePostComm.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showDialog(DIALOG_COMMENT);
			}
		});

		oneShowComm.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				final ArrayList<ProductComment> comms = Communication
						.getComments(product.idProd);
				runOnUiThread(new Runnable() {
					public void run() {
						oneCommAdapter.clear();
						for (ProductComment productComment : comms) {
							oneCommAdapter.add(productComment);
							oneCommAdapter.notifyDataSetChanged();
						}
					}
				});
			}
		});
		onePostFacebook.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// product
				Global.postOnFacebook(A1OthersInfoActivity.this,
						"Check my review on \"" + product.pName.name
								+ "\" product with Shopping Adviser!");
			}
		});
	}

	protected int getImageResource(int rate) {
		switch (rate) {
		case 1:
			return R.drawable.ok;
		case -1:
			return R.drawable.not_ok;
		default:
			return R.drawable.none;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {

		IntentResult result = IntentIntegrator.parseActivityResult(requestCode,
				resultCode, intent);
		if (result != null) { // barcode scanner
			// Handle successful scan
			System.out.println("format=" + result.getFormatName());
			System.out.println("contents=" + result.getContents());
			addProduct(result.getContents());
			return;
		}
		// else
		if (resultCode == RESULT_OK) {
			if (requestCode == RESULT_MAP_VIEW) {
				String location = intent.getStringExtra("location");
				if (location != null) {
					double latitude = intent.getDoubleExtra("latitude", 0);
					double longitude = intent.getDoubleExtra("longitude", 0);
					updateLocation = new ProductLocation(location, latitude,
							longitude);
					toUpdatePlace.setText(location);
				}
			} else if (requestCode == RESULT_TAKE_PICTURE) {
				updatePicPath = intent.getStringExtra("imagePath");
				DrawableManager.fetchLocalView(updatePicPath,
						initProductPicture);
			}
		} else if (resultCode == RESULT_CANCELED) {
			// Handle cancel
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (!Global.DEBUG_MODE)
			FlurryAgent.onStartSession(this, Global.FLURRY_ID);
	}

	@Override
	public void onStop() {
		super.onStop();
		if (!Global.DEBUG_MODE)
			FlurryAgent.onEndSession(this);
	}

}
